package cn.johnyu.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

//实际上是一个Socket的包装体，同时可以在子线程中完成与客户端交互的功能（充血模式）
public class Client implements Runnable{

    private Socket socket;
    private String name;
    private boolean running=true;
    BufferedReader reader=null;
    OutputStream outputStream = null;

    public Client(Socket socket) {
        this.socket = socket;
        try {
            reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
            outputStream = socket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //完成向指定Client发送信息的功能
    private void postMessage(String msg){
        try {
            outputStream.write((msg+"\n").getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
//    在线程池中执行的代码段
    @Override
    public void run() {
        while (running){
            try {
                //每次读取用户的输入，并使用 : 分离成为数组
                String line=reader.readLine();
                String[] infos = line.split(":");
                String action=infos[0]; //数组的第一个元素，表示为动作的类型

                switch (action){
                    case "bye": //bye 退出聊天室
                        reader.close();
                        outputStream.close();
                        socket.close();
                        ChatRoom.bye(name);
                        running=false;
                        break;
                    case "active": //进入聊天室
                        //判断token是否存在
                        String name = ChatRoom.active(infos[1], Client.this);

                        if(name!=null){
                            this.name=name;
                            postMessage("登录成功！");
                        }
                        else{
                            postMessage("请登录！");
                        }
                        break;

                    case "health": //查看聊天室的状态
                        String health = ChatRoom.health();
                        postMessage(health);
                        break;

                    case "chat": //私聊
                        Client client=ChatRoom.select(infos[1]);
                        if(client==null){
                            postMessage("该用户不在线");
                        }
                        else{
                            client.postMessage(this.name+"对你说："+infos[2]);
                        }
                        break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
